//
//  ComposeViewController.m
//  CC
//
//  Created by Calvin on 5/21/15.
//  Copyright (c) 2015 Calvin. All rights reserved.
//

#import "ComposeViewController.h"
#import "CustomTextView.h"
#import "AddTabBar.h"
#import "ComposeToolBar.h"
#import "ComposePhotosView.h"
#import "AFNetworking.h"
#import "AccountTool.h"
#import "AccountModel.h"
#import "SendStatusesParam.h"
#import "StatusTool.h"
#import "MJExtension.h"

@interface ComposeViewController()<ComposeToolBarDelegate,UITextViewDelegate,UINavigationControllerDelegate,UIImagePickerControllerDelegate>
@property (nonatomic,weak) CustomTextView *textView;
@property (nonatomic,weak) ComposeToolBar *toolBar;
@property (nonatomic,weak) ComposePhotosView *photoView;
@end

@implementation ComposeViewController
-(void)viewDidLoad
{
    [super viewDidLoad];
    [self setupNavBar];
   
    [self setupTextView];
   
    [self setupToolBar];
    
    [self setupPhoroView];
}

-(void)setupTextView
{
    CustomTextView *textView = [[CustomTextView alloc] init];
    //设置垂直方向上拥有弹簧效果
    textView.alwaysBounceVertical=YES;
    textView.delegate=self;
    textView.frame = self.view.bounds;
    [self.view addSubview:textView];
    self.textView=textView;
    
    textView.placeholder=@"分享新鲜事···";
    textView.font=[UIFont systemFontOfSize:15];
    textView.placeholderColor = [UIColor brownColor];
    
    //Listening to the keyboard
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(KeyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(KeyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
}

-(void)KeyboardWillShow:(NSNotification *)note
{
    CGFloat duration = [note.userInfo[UIKeyboardAnimationCurveUserInfoKey] doubleValue];
    [UIView animateWithDuration:duration animations:^{
        CGRect keyboardF = [note.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
        CGFloat keyboardH = keyboardF.size.height;
        self.toolBar.transform = CGAffineTransformMakeTranslation(0, -keyboardH);
    }];
}

-(void)KeyboardWillHide:(NSNotification *)note
{
    CGFloat duration = [note.userInfo[UIKeyboardAnimationCurveUserInfoKey] doubleValue];
    [UIView animateWithDuration:duration animations:^{
        self.toolBar.transform=CGAffineTransformIdentity;
    }];
}

-(void)setupNavBar
{
    self.title =@"发消息";
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationItem.leftBarButtonItem=[[UIBarButtonItem alloc]initWithTitle:@"取消" style:UIBarButtonItemStyleBordered target:self action:@selector(cancel)];
    self.navigationItem.rightBarButtonItem=[[UIBarButtonItem alloc]initWithTitle:@"发送" style:UIBarButtonItemStyleBordered target:self action:@selector(send)];
    self.navigationItem.rightBarButtonItem.enabled=NO;
}

-(void)setupToolBar
{
    ComposeToolBar *composeToolBar = [[ComposeToolBar alloc] init];
    CGSize size = CGSizeMake(self.view.frame.size.width, 44);
    CGRect frame = composeToolBar.frame;
    frame.size=size;
    composeToolBar.frame=frame;
//    self.textView.inputAccessoryView=composeToolBar;
    self.toolBar=composeToolBar;
    composeToolBar.delegate=self;
    frame.origin.y = self.view.frame.size.height-composeToolBar.bounds.size.height;
    composeToolBar.frame=frame;
    [self.view addSubview:composeToolBar];
}

-(void)setupPhoroView
{
    ComposePhotosView *composePhotoView = [[ComposePhotosView alloc] init];
    CGFloat w = self.textView.frame.size.width;
    CGFloat h = self.textView.frame.size.height;
    CGFloat y = 50;
    CGFloat x = 10;
    composePhotoView.frame = CGRectMake(x, y, w, h);
    [self.textView addSubview:composePhotoView];
    self.photoView =composePhotoView;
}

-(void)textViewDidChange:(UITextView *)textView
{
    self.navigationItem.rightBarButtonItem.enabled=self.textView.text.length!=0;
}

-(void)send
{
    NSLog(@"send message");
    if (self.photoView.images.count) {
        [self sendStatusWithImage];
    }
    else
    {
        [self sendStatusWithoutImage];
    }
}

-(void)sendStatusWithImage
{
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"access_token"] = [AccountTool accountModel].access_token;
    params[@"status"] = self.textView.text;
    
    [manager POST:@"https://upload.api.weibo.com/2/statuses/upload.json" parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        UIImage *image = [self.photoView.images firstObject];
        NSData *data = UIImageJPEGRepresentation(image, 1.0);
        [formData appendPartWithFileData:data name:@"pic" fileName:@"status.jpg" mimeType:@"image/jpeg"];
    } success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSLog(@"send with image success");
        [self dismissCurrentModel];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"send with image failed");

    }];
}

-(void)sendStatusWithoutImage
{
//    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
//    NSMutableDictionary *params = [NSMutableDictionary dictionary];
//    params[@"access_token"] = [AccountTool accountModel].access_token;
//    params[@"status"] = self.textView.text;
//    [manager POST:@"https://api.weibo.com/2/statuses/update.json" parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
//        NSLog(@"send success");
//        [self dismissCurrentModel];
//    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
//        NSLog(@"send failed");
//    }];
    SendStatusesParam *params =[[SendStatusesParam alloc] init];
    params.access_token = [AccountTool accountModel].access_token;
    params.status = self.textView.text;
    [StatusTool sendStatusesWithParam:params success:^(SendStatusesResult *result) {
        NSLog(@"send success");
        [self dismissCurrentModel];
    } failure:^(NSError *error) {
        NSLog(@"send failed");
    }];
}

-(void)cancel
{
    [self dismissCurrentModel];
}

-(void)dismissCurrentModel
{
    [self.textView endEditing:YES];
    [self dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark ComposeToolBarDelegate
-(void)composeTool:(ComposeToolBar *)toolBar didClickedButton:(ComposeToolbarButtonType)buttonType
{
    switch (buttonType) {
        case ComposeToolbarButtonTypeTrend:
    
            break;
        case ComposeToolbarButtonTypeEmotion:
            [self openEmotion];
            break;
        case ComposeToolbarButtonTypeCamera:
            [self openCamera];
            break;
        case ComposeToolbarButtonTypeMention:
            
            break;
        case ComposeToolbarButtonTypePicture:
            [self openAlbum];
            break;
    }
}

/**
 *  @author Calvin.wang, 15-05-21 21:05:40
 *
 *  view显示完毕的时候再弹出键盘，避免显示控制器view的时候会卡住
 *
 *  @param animated <#animated description#>
 */
-(void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    // 成为第一响应者（叫出键盘）
    [self.textView becomeFirstResponder];
}

-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    [self.view endEditing:YES];
}

-(void)openCamera
{
    if (![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        return;
    }
    
    UIImagePickerController *ipc = [[UIImagePickerController alloc] init];
    ipc.sourceType=UIImagePickerControllerSourceTypeCamera;
    ipc.delegate=self;
    [self presentViewController:ipc animated:YES completion:nil];
}

-(void)openAlbum
{
    if (![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
        return;
    }
    
    UIImagePickerController *ipc = [[UIImagePickerController alloc] init];
    ipc.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    ipc.delegate=self;
    [self presentViewController:ipc animated:YES completion:nil];
}

-(void)openEmotion
{
    
}

#pragma mark UIImagePickerControllerDelegate
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    [picker dismissViewControllerAnimated:YES completion:nil];
    UIImage *image = info[UIImagePickerControllerOriginalImage];
    [self.photoView addImage:image];
}

@end
